package com.walala.logic.service;

import com.alibaba.fastjson.JSON;
import com.walala.logic.common.Constant;
import com.walala.logic.dao.DataSourceManager;
import com.walala.logic.dao.MsgDao;
import com.walala.logic.dao.SessionDao;
import com.walala.logic.pojo.ChatMsgBean;
import com.walala.logic.pojo.Session;
import com.walala.logic.pojo.UserSession;
import com.walala.logic.protocol.IMProto;
import com.walala.logic.redis.RedisClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author KayLi
 */
public class ChatMsgService {

    private static Logger logger = LoggerFactory.getLogger(ChatMsgService.class);

    public static boolean saveMsg(ChatMsgBean msgBean) {

        try {
            String sessionId = msgBean.getSessionId();

            long now = System.currentTimeMillis();
            msgBean.setTime(now);

            String seqKey = Constant.Session_Seq_Key + sessionId;
            Long seqId = RedisClient.intance.getCluster().incr(seqKey);

            SessionDao sessionDao = DataSourceManager.getInstance().getSessionDao();
            MsgDao msgDao = DataSourceManager.getInstance().getMsgDao();

            Session session = sessionDao.getSessionById(sessionId);

            //不存在回话，首次创建
            if(session == null){
                session = new Session();
                session.setId(sessionId);
                session.setSessionType(msgBean.getSessionType());
                session.setSeqId(seqId);
                session.setLastMsg(msgBean.getMsgBody());
                session.setCreateTime(now);
                session.setUpdateTime(now);
                sessionDao.saveSession(session);

                //分别保存用户会话
                String[] split = sessionId.split("_");
                for (int i = 0; i < 2; i ++){
                    long userId = Long.valueOf(split[i]);
                    UserSession userSession = new UserSession();
                    userSession.setUserId(userId);
                    userSession.setSessionId(sessionId);
                    userSession.setInitSeqId(0);
                    userSession.setReadSeqId(0);
                    userSession.setCreateTime(now);
                    userSession.setUpdateTime(now);
                    sessionDao.saveUserSession(userSession);
                }

            }else{
                session.setSeqId(seqId);
                session.setLastMsg(msgBean.getMsgBody());
                session.setUpdateTime(now);
                sessionDao.updateSession(session);
            }

            //保存消息
            msgBean.setSeqId(seqId);
            msgDao.saveMsg(msgBean);
            return true;
        } catch (Exception e) {
            logger.error("saveMsg error，msg：{}", JSON.toJSONString(msgBean),e);
        }
        return false;

    }
}
